const _ = require('lodash');
const prefix = '/api/platform';
module.exports = (app) => {
    const {router, middleware} = app;

    router.get(prefix, middleware.api(), async ctx => {
        let where = {};
        if (ctx.query.hasOwnProperty('iresearch'))
            where.platform = {[app.Sequelize.Op.not]: null};
        ctx.body = await ctx.app.model.Platform.findAll({where});
    });

    //创建 修改 平台
    router.post(prefix, middleware.api(2), async ctx => {
        const data = ctx.request.body;

        if (_.isString(data.type))
            data.type = data.type.trim();
        if (_.isEmpty(data.type))
            data.type = null;

        if (data.id) {
            const platform = await ctx.model.Platform.findByPk(data.id);
            if (!platform)
                return ctx.helper.error('不存在的平台');
            await platform.update({name: data.name, url: data.url, type: data.type});
            ctx.body = platform;
        }
        else {
            ctx.body = await ctx.app.model.Platform.create(data);
        }
    });

    //删除记录
    router.del(prefix + '/:id', middleware.api(2), async ctx => {
        const row = await ctx.app.model.Platform.findByPk(ctx.params.id);
        if (!row)
            return ctx.helper.error('不存在的平台');
        await row.destroy();
        ctx.body = 'ok';
    });
};